@echo off
:: 功能：一键重新部署学生月考成绩管理系统到 Docker
:: 说明：此脚本会自动构建新镜像、停止旧容器、删除旧镜像、启动新容器
:: 容器名称：appexecel2student（后端和前端使用同一个容器）
:: 端口映射：7651（后端API）、7652（前端Web）
:: 网络：mynet

set IMAGE_NAME=appexecel2student
set CONTAINER_NAME=appexecel2student
set TEMP_IMAGE_NAME=%IMAGE_NAME%-temp

echo ========================================
echo   学生月考成绩管理系统 - Docker 重新部署
echo ========================================
echo.

:: ==================== 构建镜像 ====================
echo Step 1: Building new temporary image: %TEMP_IMAGE_NAME%
docker build -t %TEMP_IMAGE_NAME% .
if %errorlevel% neq 0 (
    echo [错误] Docker 镜像构建失败！
    pause
    exit /b 1
)

echo.
echo Step 2: Stopping and removing existing container: %CONTAINER_NAME%
docker stop %CONTAINER_NAME% >nul 2>&1
docker rm %CONTAINER_NAME% >nul 2>&1

echo.
echo Step 3: Removing old image: %IMAGE_NAME%
docker rmi %IMAGE_NAME% >nul 2>&1

echo.
echo Step 4: Tagging temporary image to final name: %IMAGE_NAME%
docker tag %TEMP_IMAGE_NAME% %IMAGE_NAME%
docker rmi %TEMP_IMAGE_NAME%

echo.
echo Step 5: Running new container: %CONTAINER_NAME%
docker run -d ^
  --name %CONTAINER_NAME% ^
  -p 7661:3000 ^
  -p 7662:80 ^
  --network=mynet ^
  --restart unless-stopped ^
  %IMAGE_NAME%

if %errorlevel% neq 0 (
    echo [错误] 容器启动失败！
    pause
    exit /b 1
)

echo.
echo ========================================
echo   重新部署完成！
echo ========================================
echo.
echo 后端 API: http://localhost:7661
echo 前端应用: http://localhost:7662
echo.
echo 容器状态:
docker ps --filter "name=%CONTAINER_NAME%"
echo.
pause
